/**
 * Created by red on 2017/4/30.
 */
import { parse } from 'utils/';
/**
 * 回答管理
 * @type {Object}
 */
export default [
  {
    name: '回答列表',
    method: 'list',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query(
        'answers',
        query => {
          if (!!data.params.question_content) query.contains('question_content', data.params.question_content);
          query.count().then(res => data.page.total = res, err => data.page.total = 0);
          query.skip((data.page.current_page - 1) * data.page.page_size);
          query.limit(data.page.page_size);
        }
      ).filter(x => x.type && x.type === 'result')
        .map(x => {
          return x.result.map(item => ({
            id: item.id,
            question_content: item.get('question_content'),
            question_id: item.get('question_id'),
            answer: item.get('answer'),
            answer_index: item.get('answer_index'),
            is_correct: item.get('is_correct'),
          }));
        })
        .subscribe(fn, errFn);
    }
  },
  {
    name: '查询回答',
    method: 'find',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query('answers', query => query.equalTo('objectId', data))
        .filter(x => x.type && x.type === 'result')
        .map(x => {
          return x.result.map(item => ({
            id: item.id,
            question_content: item.get('question_content'),
            question_id: item.get('question_id'),
            answer: item.get('answer'),
            answer_index: item.get('answer_index'),
            is_correct: item.get('is_correct'),
          }));
        })
        .subscribe(next => fn(next[0]));
    }
  },
  {
    name: '新增回答',
    method: 'create',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      parse.create('answers', data).subscribe(fn, errFn);
    }
  },
  {
    name: '修改回答',
    method: 'update',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query('answers', query => query.equalTo('objectId', data.id))
        .filter(x => x.type && x.type === 'result')
        .map(x => x.result[0])
        .subscribe(res => {
          parse.update(res, data.data).subscribe(fn, errFn);
        });
    }
  },
  {
    name: '删除回答',
    method: 'delete',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query('answers', query => query.equalTo('objectId', data))
        .filter(x => x.type && x.type === 'result')
        .map(x => x.result[0])
        .subscribe(res => {
          parse.delete(res).subscribe(fn, errFn);
        });
    }
  }
];